﻿namespace DesignModeConsole.行为型.命令模式;

/// <summary>
/// 命令模式服务
/// </summary>
public class CommandService : IService
{
    private static readonly Queue<IRequestCommand> queue = new Queue<IRequestCommand>();

    public void Main()
    {
        _ = queue.EnsureCapacity(5);

        // 后台消费请求
        HandlerReqestBackgroupService();

        // 前端生产请求
        while (true)
        {
            var requests = new List<IRequestCommand>();

            #region 伪造请求

            var random = new Random();
            for (var i = 0; i < random.Next(1, 5); i++)
            {
                if (i % 2 == 0)
                {
                    requests.Add(new SendSmsCommand());
                }
                else
                {
                    requests.Add(new SendEmailCommand());
                }
            }

            #endregion

            foreach (var request in requests)
            {
                IRequestCommand command = null;
                if (request is SendSmsCommand sendSmsCommand)
                {
                    command = sendSmsCommand;
                }
                else if (request is SendEmailCommand sendEmailCommand)
                {
                    command = sendEmailCommand;
                }

                queue.Enqueue(command);
            }

            Thread.Sleep(1000);
        }
    }

    private void HandlerReqestBackgroupService()
    {
        Task.Factory.StartNew(async () =>
        {
            while (true)
            {
                while (queue.Count != 0)
                {
                    await Console.Out.WriteLineAsync($"当前队列容量：{queue.Count}");
                    var command = queue.Dequeue();
                    command.Excute();
                    await Task.Delay(1000);
                }
            }
        });
    }
}

public interface IRequestCommand
{
    void Excute();
}

/// <summary>
/// 发送短信
/// </summary>
public class SendSmsCommand : IRequestCommand
{
    public void Excute()
    {
        Console.WriteLine("发送短信" + DateTime.Now);
    }
}

/// <summary>
/// 发送邮件
/// </summary>
public class SendEmailCommand : IRequestCommand
{
    public void Excute()
    {
        Console.WriteLine("发送邮件" + DateTime.Now);
    }
}